//
//  YManagerViewController.m
//  shijianpinggu
//
//  Created by apple on 2017/1/5.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YManagerViewController.h"
#import "YManageTableViewCell.h"
#import "YMaUserTableViewCell.h"
#import "messageModel.h"


@interface YManagerViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *voiceButton;
- (IBAction)voiceButtonAction:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UITextField *massageText;
@property (weak, nonatomic) IBOutlet UIView *textView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewH;

@property(nonatomic,assign)NSInteger keyBHeigh;

@property(nonatomic,assign)NSInteger massageNum;
@property(nonatomic,strong)NSMutableArray *mineMassage;
@property(nonatomic,strong)NSMutableArray *lineMassage;
@property(nonatomic,assign)CGFloat cellHeigh;
@property(nonatomic,strong)messageModel *meModel;

@end

@implementation YManagerViewController

-(NSMutableArray *)mineMassage{
    if (!_mineMassage) {
        _mineMassage = [[NSMutableArray alloc] init];
    }
    return _mineMassage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
    self.title = @"在线支持";
    self.tableView.separatorStyle = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.massageText.delegate = self;
    self.massageNum = 0;
    
    self.voiceButton.layer.cornerRadius = 4;
    self.voiceButton.layer.masksToBounds = YES;
    
    [self loadUpWithUrl];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"YManageTableViewCell" bundle:nil] forCellReuseIdentifier:@"managecell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"YMaUserTableViewCell" bundle:nil] forCellReuseIdentifier:@"meusercell"];
    
    UIButton *rifhtButton = [[UIButton alloc] init];
    rifhtButton.frame = CGRectMake(0, 0, 20, 20);
    [rifhtButton addTarget:self action:@selector(rifhtButtonAction) forControlEvents:UIControlEventTouchUpInside];
    rifhtButton.backgroundColor = [UIColor clearColor];
    [rifhtButton setImage:[UIImage imageNamed:@"dianhua"] forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rifhtButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    

    
    
}

-(void)tableviewWhatRow{
    NSUInteger sectionCount = [self.tableView numberOfSections];
    
    if (sectionCount) {
        
        
        
       
        
        if (self.mineMassage) {
            
            
            
            //NSUInteger ii[2] = {0, rowCount - 1};
            
           
            
            [self.tableView scrollToRowAtIndexPath:
             
             [NSIndexPath indexPathForRow:[self.mineMassage count]-1 inSection:0]
             
                                      atScrollPosition: UITableViewScrollPositionBottom
             
                                              animated:NO];
            
        }
        
    }
}
-(void)loadUpWithUrl{
   
    
       NSDictionary *parameter = @{@"contactid":[[NSUserDefaults standardUserDefaults] stringForKey:@"userid"]};
    
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/Leaving/messagelist" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@", dic);
    
        
    
        NSArray *array = dic[@"list"];
        
        if (![dic[@"list"]  isEqual: @""]) {
            for (NSDictionary *dic in array) {
    
                messageModel *model = [messageModel new];
                [model setValuesForKeysWithDictionary:dic];
                CGRect newSize = [model.content boundingRectWithSize:CGSizeMake(self.view.frame.size.width/2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
                
                model.cellHeigh = newSize.size.height;
                model.cellwith = newSize.size.width+20;
                [self.mineMassage addObject:model];
            }
            
            
            [self.tableView reloadData];
            [self tableviewWhatRow];
        }
               
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.mineMassage.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    messageModel *model = self.mineMassage[indexPath.row];
    if ([model.is_concatadm isEqualToString: @"0"]) {
        YMaUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"meusercell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.massageLabel.text = model.content;
        
        UIImage *image = [UIImage imageNamed:@"lan_kkkk"];

        image = [image stretchableImageWithLeftCapWidth:image.size.width/2 topCapHeight:image.size.height/2+10];
//       image = [image resizableImageWithCapInsets:(UIEdgeInsets){10,20,15,0} resizingMode:UIImageResizingModeStretch];
//         //{top/scale,left/scale,bottom/scale,right/scale}  top  left bottom right 表示图片不拉伸的尺寸.
        cell.massgeImage.image = image;
//            [leftBubble resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 100)];
        //创建这俩个view 即气泡view他们将加到cell的contentview上
        
        //大小会改变的，只有位置不变  bounds会改变的
        cell.massageWidth.constant = model.cellwith;
        cell.massageHeigh.constant = model.cellHeigh;        return cell;

    }else{
    
    YManageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"managecell" forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
        cell.massageLabel.text = model.content;
        
        
        cell.massgeImage.image = [cell.massgeImage.image stretchableImageWithLeftCapWidth:cell.massgeImage.image.size.width/2 topCapHeight:cell.massgeImage.image.size.height/2+10];
//        cell.massgeImage.image = [cell.massgeImage.image resizableImageWithCapInsets:UIEdgeInsetsMake(cell.massgeImage.image.size.width/2 ,cell.massgeImage.image.size.height/2+20, 5, 5)];
        
        //    [leftBubble resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 100)];
        //创建这俩个view 即气泡view他们将加到cell的contentview上
        
        //大小会改变的，只有位置不变  bounds会改变的
        
//        CGRect newSize = [cell.massageLabel.text boundingRectWithSize:CGSizeMake(cell.massageLabel.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
        cell.massageWidth.constant = model.cellwith;
        cell.massageHeigh.constant = model.cellHeigh;
        return cell;
        
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%f",self.cellHeigh);
    return 30+[[self.mineMassage[indexPath.row] valueForKey:@"cellHeigh"] intValue];
}


-(void)rifhtButtonAction{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"13911483759"];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    
}

//回收键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.massageText resignFirstResponder];
   
    
    
}

//根据键盘调整界面
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    
     
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    self.keyBHeigh = keyboardRect.size.height;
    int width = keyboardRect.size.width;
    NSLog(@"键盘高度是  %ld",(long)_keyBHeigh);
    NSLog(@"键盘宽度是  %d",width);
    CGRect fram = self.view.frame;
    fram.origin.y = self.view.frame.origin.y-self.keyBHeigh/2;
    
    self.textViewH.constant =  self.keyBHeigh ;
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    CGRect fram = self.view.frame;
    fram.origin.y = self.view.frame.origin.y-self.keyBHeigh/2;
    
    self.textViewH.constant = 49 ;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"aaaa");
    
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)voiceButtonAction:(UIButton *)sender {
    NSLog(@"aaa");
    if (!([self.massageText.text isEqualToString:@""])) {
        [self loadUpMessage:self.massageText.text];
        messageModel *model = [messageModel new];
        model.is_concatadm = @"0";
        model.content = self.massageText.text;
        CGRect newSize = [self.massageText.text boundingRectWithSize:CGSizeMake(200, [UIScreen mainScreen].bounds.size.width-60) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
        model.cellHeigh = newSize.size.height;
        [self.mineMassage addObject:model];
        [self.tableView reloadData];
        
        
    }
    self.massageText.text = nil;
    [self.massageText resignFirstResponder];
    
    
    CGRect fram = self.view.frame;
    NSLog(@"%f",self.view.frame.origin.y);
    fram.origin.y = 64;
    self.textView.frame = fram;
    NSLog(@"%@",self.mineMassage);
    [self.tableView reloadData];
    [self tableviewWhatRow];
}
-(void)loadUpMessage:(NSString *)message{
   
    
    NSDictionary *parameter = @{@"contactid":[[NSUserDefaults standardUserDefaults] stringForKey:@"userid"],@"Content":message};
    
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/Leaving/message" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@", dic);
        if ([dic[@"code"] integerValue]==200) {
            
            
            NSLog(@"发送成功");
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
}

@end
